#!/usr/bin/env python3
"""
Graph Backend 启动脚本
用于启动CSV数据解析和图谱生成的后端服务
"""

import os
import sys
import subprocess
import time
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 7):
        print("❌ 错误: 需要Python 3.7或更高版本")
        print(f"当前版本: {sys.version}")
        return False
    print(f"✅ Python版本检查通过: {sys.version}")
    return True

def install_requirements():
    """安装依赖包"""
    requirements_file = Path(__file__).parent / "requirements.txt"
    
    if not requirements_file.exists():
        print("❌ 错误: requirements.txt文件不存在")
        return False
    
    print("📦 正在安装依赖包...")
    try:
        subprocess.check_call([
            sys.executable, "-m", "pip", "install", "-r", str(requirements_file)
        ])
        print("✅ 依赖包安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 安装依赖包失败: {e}")
        return False

def create_upload_directory():
    """创建上传目录"""
    upload_dir = Path(__file__).parent / "uploads"
    upload_dir.mkdir(exist_ok=True)
    print(f"✅ 上传目录已创建: {upload_dir}")

def start_server():
    """启动Flask服务器"""
    print("\n🚀 正在启动Graph Backend服务器...")
    print("📍 服务地址: http://localhost:5000")
    print("📋 API端点:")
    print("   - GET  /api/health - 健康检查")
    print("   - POST /api/upload-csv - 上传CSV文件")
    print("   - POST /api/process-csv-data - 处理CSV数据")
    print("   - GET  /api/sample-data - 获取示例数据")
    print("\n按 Ctrl+C 停止服务器\n")
    
    try:
        # 启动Flask应用
        from app import app
        app.run(debug=True, host='0.0.0.0', port=5000)
    except KeyboardInterrupt:
        print("\n👋 服务器已停止")
    except Exception as e:
        print(f"❌ 启动服务器失败: {e}")

def main():
    """主函数"""
    print("=" * 50)
    print("🎯 Graph Backend - CSV数据解析服务")
    print("=" * 50)
    
    # 检查Python版本
    if not check_python_version():
        return
    
    # 安装依赖
    if not install_requirements():
        return
    
    # 创建必要目录
    create_upload_directory()
    
    # 启动服务器
    start_server()

if __name__ == "__main__":
    main()







